package com.yonyou.base.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.yonyou.hrcloud.adder.data.json.Json2ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据对象工具集合类
 */
public class JsonHelper {

    private static final Logger log = LoggerFactory.getLogger(JsonHelper.class);

    /**
     * json转VO
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T readValue(String data, Class<T> clazz) {
        if (StringUtils.isBlank(data)) {
            return null;
        }
        try {
            return Json2ObjectMapper.getInstance().readValue(data, clazz);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * json转Map
     *
     * @param data
     * @return
     */
    public static Map<String, Object> readMapValue(String data) {
        if (StringUtils.isBlank(data)) {
            return null;
        }
        try {
            return Json2ObjectMapper.getInstance().readValue(data, LinkedHashMap.class);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * json转List
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> readListValue(String data, Class<T> clazz) {
        if (StringUtils.isBlank(data)) {
            return null;
        }
        try {
            return Json2ObjectMapper.getInstance().readValue(data, TypeFactory.defaultInstance().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 对象转json
     *
     * @param object
     * @return
     */
    public static String writeValue(Object object) {
        if (object == null) {
            return null;
        }
        try {
            return Json2ObjectMapper.getInstance().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
